package chenbi.renthouse.service.impl;

import chenbi.renthouse.controller.dto.LoginDTO;
import chenbi.renthouse.controller.request.LoginRequest;
import chenbi.renthouse.controller.request.UserPageRequest;
import chenbi.renthouse.entity.User;
import chenbi.renthouse.exception.ServiceException;
import chenbi.renthouse.mapper.UserMapper;
import chenbi.renthouse.service.IUserService;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.IdUtil;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Slf4j
@Service
public class UserService implements IUserService {

    @Autowired(required = false)
    UserMapper userMapper;

    @Override
    public List<User> list() {
        return userMapper.list();
    }

    @Override
    public Object page(UserPageRequest userPageRequest) {
        PageHelper.startPage(userPageRequest.getPageNum(),userPageRequest.getPageSize());
        List<User> users = userMapper.listByCondition(userPageRequest);
        return new PageInfo<>(users);
    }

    @Override
    public void save(User user) {
        Date date = new Date();
        // 当做卡号来处理
//        user.setAccount(0);
        user.setUseraccount(DateUtil.format(date,"yyyyMMdd")+Math.abs(IdUtil.fastSimpleUUID().hashCode()));
        userMapper.save(user);
    }

    @Override
    public User getById(Integer id) {
        return userMapper.getById(id);
    }

    @Override
    public void update(User user) {
//        user.setUpdatetime((java.sql.Date) new Date());
        userMapper.updateById(user);
    }

    @Override
    public void deleteById(Integer id) {
        userMapper.deleteById(id);
    }

    @Override
    public LoginDTO login(LoginRequest request) {
            User user =userMapper.getByUsernameAndPassword(request);
            if (user == null){
                throw new ServiceException("用户名或密码错误");

            }
            LoginDTO loginDTO = new LoginDTO();
            BeanUtils.copyProperties(user,loginDTO);
            return loginDTO;

    }

}








